<template>
	<div class="coupon">
		<use-table ref="tbl" :tableRefs="$refs.etbl"></use-table>
		<div class="container_status dflex_vertical_c">
			<div class="item_interval" v-for="(item, i) in stateDatas" :key="i">
				<el-button class="badge_txt" :class="{ active: item.name == state }" size="small" @click="cutSta(item)">
					{{ item.name }}
				</el-button>
				<v-countup class="badge" start-value="0" :end-value="item.cnt"></v-countup>
			</div>
		</div>
		<div class="container padding_b_0">
			<div class="dflex_wrap">
				<div class="dflex_vertical_c margin_r_40 margin_b_20">
					<div class="search_name">名称：</div>
					<el-input v-model="req.name" placeholder="请输入" class="search_input" @change="search" clearable>
					</el-input>
				</div>
				<div class="dflex_vertical_c margin_r_40 margin_b_20" v-if="advancedSearch">
					<div class="search_name">类型：</div>
					<el-select v-model="req.type" class="search_input" @change="search">
						<el-option v-for="item in typeOptions" :key="item.value" :label="item.label"
							:value="item.value"></el-option>
					</el-select>
				</div>
				<div class="dflex_vertical_c margin_r_40 margin_b_20" v-if="advancedSearch">
					<div class="search_name">创建时间：</div>
					<el-date-picker v-model="searchTime" type="daterange" align="right" range-separator="至"
						start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd"
						:picker-options="pickerTimeOptions" class="search_start_end_time" @change="search">
					</el-date-picker>
				</div>
				<el-button size="mini" :loading="searchBtnLoading" class="search-btn margin_b_20 margin_r_40"
					@click="search">搜索</el-button>
				<div class="search_advanced margin_b_20" @click="advancedSearch = !advancedSearch"
					v-if="!advancedSearch">高级筛选</div>
				<div class="search_common margin_b_20" @click="advancedSearch = !advancedSearch" v-if="advancedSearch">
					常用筛选</div>
			</div>
		</div>
		<div class="container last_container use-table">
			<div class="dflex_sb margin_b_15 table-head">
				<el-button class="batch-btn padding0" :loading="removesBtnLoading" @click="removes">删除<span
						v-if="selectDatas.length">×{{selectDatas.length}}</span></el-button>
				<el-button class="add-btn pos_r padding0" icon="iconfont iconxinzeng" @click="toAdd">新增</el-button>
			</div>
			<el-table ref="etbl" :height="tblHeight" v-loading="tableLoading" :data="tableDatas"
				@selection-change="selectionChange" highlight-current-row>
				<el-table-column type="selection" :selectable="selectable"></el-table-column>
				<el-table-column property="name" label="名称" align="center" width="150"></el-table-column>
				<el-table-column property="type" label="类型" align="center"></el-table-column>
				<el-table-column label="面值" align="center">
					<template slot-scope="scope">
						<div>{{ scope.row.price / 100 }}{{ scope.row.type == '满减' ? '元' : '折' }}</div>
					</template>
				</el-table-column>
				<el-table-column label="消费满减" align="center">
					<template slot-scope="scope">
						<div v-if="scope.row.order_amount == 0">不限</div>
						<div v-else>{{ scope.row.order_amount }} 元</div>
					</template>
				</el-table-column>
				<el-table-column property="per_max" label="可领数" align="center">
					<template slot-scope="scope">
						<div v-if="scope.row.per_max == 0">不限</div>
						<div v-else>{{ scope.row.per_max }}张</div>
					</template>
				</el-table-column>
				<el-table-column label="发行数量" align="center">
					<template slot-scope="scope">
						<div>{{ scope.row.num }}张</div>
					</template>
				</el-table-column>
				<el-table-column label="剩余券" align="center">
					<template slot-scope="scope">
						<div>{{ scope.row.num - scope.row.receive_num }}张</div>
					</template>
				</el-table-column>
				<el-table-column property="member_type" label="用户类型" align="center"></el-table-column>
				<el-table-column property="receive_type" label="领取方式" align="center"></el-table-column>
				<el-table-column property="state" label="状态" align="center"></el-table-column>
				<el-table-column property="start_time" label="生效时间" align="center" width="180"></el-table-column>
				<el-table-column property="end_time" label="过期时间" align="center" width="180"></el-table-column>
				<el-table-column label="描述" align="center" width="100">
					<template slot-scope="scope">
						<el-popover :open-delay="350" :close-delay="80" placement="left" trigger="hover"
							:content="scope.row.note + ''">
							<div slot="reference" class="ellipsis crpr">{{ scope.row.note }}</div>
						</el-popover>
					</template>
				</el-table-column>
				<el-table-column label="备注" align="center" width="100">
					<template slot-scope="scope">
						<el-popover :open-delay="350" :close-delay="80" placement="left" trigger="hover"
							:content="scope.row.remark + ''">
							<div slot="reference" class="ellipsis crpr">{{ scope.row.remark }}</div>
						</el-popover>
					</template>
				</el-table-column>
				<el-table-column property="create_time" label="创建时间" align="center" width="180"></el-table-column>
				<el-table-column label="操作" align="center" fixed="right" width="150">
					<template slot-scope="scope">
						<el-tooltip :open-delay="350" v-if="scope.row.state == '待激活'" content="激活" placement="top"
							:hide-after="1000" :enterable="false" effect="light">
							<el-button circle size="medium" icon="el-icon-thumb" class="table-btn"
								@click="activation(scope.row._id)"></el-button>
						</el-tooltip>
						<el-tooltip :open-delay="350"
							v-if="scope.row.state == '运营中' && scope.row.receive_type == '主动发放'" content="赠送"
							placement="top" :hide-after="1000" :enterable="false" effect="light">
							<el-button circle size="medium" icon="el-icon-present" class="table-btn"
								@click="giftCoupon(scope.row)"></el-button>
						</el-tooltip>
						<el-tooltip :open-delay="350" v-if="scope.row.state !== '待激活'" content="详情" placement="top"
							:hide-after="1000" :enterable="false" effect="light">
							<el-button circle size="medium" icon="el-icon-more-outline" class="table-btn"
								@click="toDetail(scope.row._id)"></el-button>
						</el-tooltip>
						<el-tooltip :open-delay="350" v-if="scope.row.state == '待激活'" content="编辑" placement="top"
							:hide-after="1000" :enterable="false" effect="light">
							<el-button circle size="medium" icon="el-icon-edit" class="table-btn"
								@click="toEdit(scope.row._id)"></el-button>
						</el-tooltip>
						<el-tooltip :open-delay="350" v-if="scope.row.state !== '运营中'" content="删除" placement="top"
							:hide-after="1000" :enterable="false" effect="light">
							<el-button circle size="medium" icon="el-icon-delete" class="table-btn"
								@click="remove(scope.row._id)"></el-button>
						</el-tooltip>
					</template>
				</el-table-column>
				<div slot="empty">
					<el-empty description=" "></el-empty>
				</div>
			</el-table>
			<el-pagination background :current-page="req.page" :page-sizes="[10, 20, 30, 50, 100]" :page-size="req.rows"
				layout="total, sizes, prev, pager, next, jumper" :total="tableTotal" @size-change="sizeChange"
				@current-change="currentChange"></el-pagination>
		</div>
		<el-drawer title="赠送" size="500px" :visible.sync="giftCouponDrawer" direction="rtl" :append-to-body="true"
			:wrapperClosable="false" @open="drawerOpen">
			<el-form class="add_edit" :model="giftCouponForm" :rules="giftCouponRules" ref="ruleForm"
				label-width="100px">
				<el-form-item label="可领数">
					<el-input disabled :value="perMax == 0 ? '不限' : perMax"></el-input>
				</el-form-item>
				<el-form-item label="剩余券">
					<el-input disabled v-model="residue"></el-input>
					<div class="remark_txt" v-if="residue == 0">剩余卷为0不可赠送</div>
				</el-form-item>
				<el-form-item label="数量" prop="num" ref="num">
					<el-input v-model.number="giftCouponForm.num" type="number" :min="0" @input="numChange"
						:disabled="residue == 0" clearable></el-input>
				</el-form-item>
				<el-form-item label="用户" prop="openids" ref="openids">
					<el-select v-model="giftCouponForm.openids" class="multiple-select" filterable remote multiple
						placeholder="请输入用户名称" :clearable="true" :remote-method="getMember" :loading="giftCouponLoading"
						@change="seleChange" :disabled="residue == 0 || giftDisabled">
						<el-option v-for="item in memberOptions" :key="item.value" :label="item.label"
							:value="item.value">
							<div class="dflex_vertical_c">
								<el-avatar :size="30" :src="item.headimg"></el-avatar>
								<span class="margin_l_10">{{ item.label }}</span>
							</div>
						</el-option>
					</el-select>
					<div class="dflex">
						<div v-if="giftCouponForm.openids.length >= 1" class="remark_txt margin_r_20">
							还可选{{ userNum - giftCouponForm.openids.length < 0 ? 0 : userNum - giftCouponForm.openids.length }}个用户
						</div>
						<div class="remark_txt">最多可选{{ userNum }}个用户</div>
					</div>
				</el-form-item>
			</el-form>
			<div class="gift">
				<div class="gift_item pos_r dflex_vertical_c dflex_d_c" v-for="(item, i) in seleMember" :key="i">
					<el-image class="headimg"
						:src="item.data.member_headimg || 'https://7463-tcb-rflrz31u8yan4rr9ad60d-268679-1308293149.tcb.qcloud.la/1659579992133_0.png'"
						:preview-src-list="item.previewImgs" fit="cover"></el-image>
					<div slot="reference" class="ellipsis">{{ item.data.member_name }}</div>
					<div class="el-icon-close crpr pos_a" @click="giftRemove(item.data)"></div>
				</div>
			</div>
			<div class="btn pos_a">
				<el-button :loading="giftLoading" round icon="el-icon-check" class="confirm-btn"
					:disabled="residue == 0 || giftDisabled" @click="submitForm('ruleForm')">提交</el-button>
				<el-button round icon="el-icon-back" class="return-btn" @click="giftCouponDrawer = false">返回</el-button>
			</div>
		</el-drawer>
	</div>
</template>

<script>
	import vCountup from 'vue-countupjs';
	const __name = 'wmzmall-marketing-coupon-rule';
	const __member = 'wmzmall-member';
	export default {
		components: {
			vCountup
		},
		data() {
			const validateNum = async (rule, value, callback) => {
				if (!value) {
					return callback(new Error('请输入赠送数量'));
				}

				if (value < 0) {
					return callback(new Error('请输入正确的数量'));
				}

				if (value > this.perMax && this.perMax > 0) {
					return callback(new Error('赠送数量不可大于可领数量'));
				}

				if (value > this.residue && this.perMax == 0) {
					callback(new Error('赠送数量不能大于剩余数量'));
					this.giftDisabled = true;
				} else {
					this.giftDisabled = false;
				}

				callback();
			};
			const validateOpenids = async (rule, value, callback) => {
				if (value.length == 0 && this.residue > 0) {
					callback(new Error('请输入选择赠送用户'));
				}

				if (value.length > this.userNum) {
					callback(new Error('赠送用户数不能大于剩余数量'));
				}

				callback();
			};
			return {
				state: '全部',
				stateObj: {
					待激活: 0,
					运营中: 0,
					已过期: 0,
					全部: 0
				},
				stateDatas: [],
				advancedSearch: false,
				searchTime: [],
				typeOptions: [{
						value: '',
						label: '全部'
					},
					{
						value: '满减',
						label: '满减'
					},
					{
						value: '折扣',
						label: '折扣'
					}
				],
				req: {
					page: 1,
					rows: 10,
					orderby: 'create_time desc',
					state: '',
					name: '',
					type: '',
					begin_time: '',
					end_time: ''
				},
				tblHeight: 0,
				tableLoading: false,
				tableDatas: [],
				tableTotal: 0,
				selectDatas: [],
				pickerTimeOptions: {
					disabledDate(time) {
						return time.getTime() > Date.now();
					},
					shortcuts: [{
							text: '最近一周',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
								picker.$emit('pick', [start, end]);
							}
						},
						{
							text: '最近一个月',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
								picker.$emit('pick', [start, end]);
							}
						},
						{
							text: '最近三个月',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
								picker.$emit('pick', [start, end]);
							}
						}
					]
				},
				giftCouponDrawer: false,
				couponId: 0,
				giftLoading: false,
				residue: 0,
				perMax: 0,
				userNum: 0,
				giftDisabled: false,
				giftCouponLoading: false,
				memberOptions: [],
				giftCouponForm: {
					num: 1,
					openids: []
				},
				giftCouponRules: {
					num: [{
						required: true,
						validator: validateNum,
						trigger: 'change'
					}],
					openids: [{
						required: true,
						validator: validateOpenids,
						trigger: 'change'
					}]
				},
				seleMap: new Map(),
				seleMember: [],
				searchBtnLoading: false,
				removesBtnLoading: false
			};
		},
		methods: {
			async loadData(callback) {
				this.tableLoading = true;

				this.stateDatas = [];
				for (let key in this.stateObj) {
					this.stateDatas.push({
						name: key,
						cnt: this.stateObj[key]
					});
				}

				this.req.begin_time = '';
				this.req.end_time = '';

				if (this.searchTime && this.searchTime.length > 0) {
					this.req.begin_time = this.searchTime[0].getTime();
					this.req.end_time = this.searchTime[1].getTime() + (60 * 60 * 24 - 1) * 1000;
				}

				await this.$db[__name]
					.whereif(this.req.state && this.req.state != '全部', {
						state: this.req.state
					})
					.whereif(this.req.name, {
						name: new RegExp(this.$api.filterRegexpKey(this.req.name), 'i')
					})
					.whereif(this.req.type, {
						type: this.req.type
					})
					.whereif(this.searchTime && this.searchTime.length > 0, {
						create_time: this.$db.$cmd.gte(this.req.begin_time).and(this.$db.$cmd.lte(this.req
							.end_time))
					})
					.withgroup({
						field: 'state',
						obj: this.stateObj
					})
					.totable(this.req)
					.then(res => {
						if (res.code == 200) {
							if (res.datas.group && res.datas.group.datas) {
								this.stateDatas = res.datas.group.datas;
							}

							res.datas.rows.forEach((row, idx) => {
								row.start_time = new Date(row.start_time).format();
								row.end_time = new Date(row.end_time).format();
								row.create_time = new Date(row.create_time).format();
							});

							this.tableDatas = res.datas.rows;
							this.tableTotal = res.datas.total;

							if (typeof callback === 'function') {
								callback();
							}
						}
						this.searchBtnLoading = false;
						this.tableLoading = false;
					});
			},
			search() {
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);
				this.searchBtnLoading = true;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});

				uni.setStorage({
					key: '__search' + this.$route.path,
					data: this.req
				});
			},
			toAdd() {
				uni.navigateTo({
					url: `/pages/marketing/coupon/coupon_add_edit?tab=添加优惠券`,
					events: {
						refreshData: () => {
							this.loadData();
						}
					}
				});
			},
			toEdit(id) {
				uni.navigateTo({
					url: `/pages/marketing/coupon/coupon_add_edit?id=${id}&tab=编辑优惠券`,
					events: {
						refreshData: () => {
							this.loadData();
						}
					}
				});
			},
			toDetail(id) {
				uni.navigateTo({
					url: `/pages/marketing/coupon/detail?id=${id}&tab=优惠券详情`,
					events: {
						refreshData: () => {
							this.loadData();
						}
					}
				});
			},
			remove(id) {
				this.$confirm('此操作将删除该优惠券!', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$db[__name].remove(id).then(res => {
						if (res.code == 200) {
							this.loadData();
						}
					});
				});
			},
			selectionChange(datas) {
				this.selectDatas = datas;
			},
			selectable(datas) {
				if (datas.state == '待激活') {
					return true;
				}

				return false;
			},
			removes() {
				if (this.selectDatas.length <= 0) {
					this.$message('请勾选需要删除的数据！');
					return;
				}

				let ids = this.selectDatas.map(x => x._id);

				this.$confirm('此操作将永久删除勾选数据！', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.removesBtnLoading = true;
					this.$db[__name]
						.where({
							_id: this.$db.$cmd.in(ids)
						})
						.remove()
						.then(res => {
							if (res.code == 200) {
								this.loadData();
							}
							this.removesBtnLoading = false;
						}).catch(() => {
							this.removesBtnLoading = false;
						})
				});
			},
			activation(id) {
				this.$confirm('此操作将激活优惠券!', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$func.wmzadmin.call('coupon/activation', {
						id: id
					}).then(res => {
						if (res.code == 200) {
							this.$message({
								message: res.datas,
								type: 'success'
							});
							this.loadData();
						}
					});
				});
			},
			giftCoupon(row) {
				this.giftCouponForm.num = 1;
				this.giftCouponForm.openids = [];
				this.seleMember = [];
				this.residue = row.num - row.receive_num;
				this.perMax = row.per_max;
				this.userNum = this.residue / this.giftCouponForm.num;
				this.giftCouponDrawer = true;
				this.couponId = row._id;
			},
			drawerOpen() {
				if (this.$refs.ruleForm) {
					this.$refs.ruleForm.clearValidate();
				}
			},
			async getMember(keyword) {
				if (keyword !== '') {
					this.giftCouponLoading = true;
					await this.$db[__member]
						.whereif(keyword, {
							member_name: new RegExp(keyword)
						})
						.tolist({
							rows: 30,
							loading: false
						})
						.then(res => {
							if (res.code == 200) {
								this.giftCouponLoading = false;
								this.memberOptions = [];
								res.datas.forEach(data => {
									this.memberOptions.push({
										value: data._id,
										label: data.member_name,
										headimg: data.member_headimg ||
											'https://7463-tcb-rflrz31u8yan4rr9ad60d-268679-1308293149.tcb.qcloud.la/1659579992133_0.png',
										previewImgs: [data.member_headimg ||
											'https://7463-tcb-rflrz31u8yan4rr9ad60d-268679-1308293149.tcb.qcloud.la/1659579992133_0.png'
										],
										data: data
									});
								});
							}
						});
				} else {
					this.memberOptions = [];
				}
			},
			seleChange() {
				this.memberOptions
					.filter(x => this.giftCouponForm.openids.find(d => x.value == d))
					.forEach(x => {
						this.seleMap.set(x.data._id, x);
					});

				[...this.seleMap.keys()].forEach(x => {
					if (!this.giftCouponForm.openids.find(d => d == x)) {
						this.seleMap.delete(x);
					}
				});

				this.seleMember = [...this.seleMap.values()];
			},
			giftRemove(item) {
				this.seleMap.delete(item._id);
				this.giftCouponForm.openids = [...this.seleMap.keys()];
				this.seleMember = [...this.seleMap.values()];
			},
			numChange(value) {
				this.userNum = parseInt(this.residue / value) || 0;
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid, obj) => {
					// 默认获取第一个未验证 form 属性名
					this.$api.set_unvalidated_form_focus(this, obj);
					if (valid) {
						this.giftLoading = true;
						this.$func.wmzadmin.call('coupon/gift', {
							id: this.couponId,
							giftData: this.giftCouponForm
						}).then(res => {
							if (res.code == 200) {
								this.$message({
									message: res.datas,
									type: 'success'
								});
								this.giftCouponDrawer = false;
								this.loadData();
							}
							this.giftLoading = false;
						});
					}
				});
			},
			cutSta(item) {
				uni.setStorage({
					key: '__cutSta' + this.$route.path,
					data: item
				});

				this.state = item.name;
				this.req.state = item.name;
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			},
			sizeChange(size) {
				this.$api.storagePaginationRows(size, this.$route.path);
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);
				this.req.rows = size;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			},
			currentChange(current) {
				this.$api.storagePaginationPage(current, this.$route.path);
				this.req.page = current;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			}
		},
		created() {
			let __search = uni.getStorageSync('__search' + this.$route.path);
			if (__search) {
				this.req = __search;
				if (this.req.type) {
					this.advancedSearch = true;
				}
				if (this.req.begin_time && this.req.end_time) {
					this.searchTime.push(new Date(this.req.begin_time), new Date(this.req.end_time));
					this.advancedSearch = true;
				}
			}

			let thisCutSta = uni.getStorageSync('__cutSta' + this.$route.path);
			this.state = '全部';
			this.req.page = 1;
			this.req.state = this.state;
			if (thisCutSta) {
				this.state = thisCutSta.name;
				this.req.state = thisCutSta.name;
			}
			this.req.page = uni.getStorageSync('__paginationPage' + this.$route.path) || 1;
			this.req.rows = uni.getStorageSync('__paginationRows' + this.$route.path) || 10;

			this.loadData(() => {
				this.$nextTick(() => {
					this.$api.scrollToStorage('.el-table__body-wrapper', this.$route.path);
				});
			});
		},
		mounted() {
			this.$nextTick(() => {
				this.$api.scrollOnStorage('.el-table__body-wrapper', this.$route.path);
			});
		},
		updated() {
			if (!this.tblHeight) {
				this.tblHeight = this.$refs.tbl.tblHeight;
			}
		}
	};
</script>

<style>
	.add_edit>>>.el-select.multiple-select {
		width: 80%;
	}

	.coupon .ellipsis {
		width: 100px;
	}

	.gift {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		grid-gap: 16px 16px;
		margin: 0 16px 0 16px;
	}

	.gift_item {
		padding: 20px;
		background-color: #fff;
		border-radius: 10px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	}

	.gift_item .ellipsis {
		width: 100px;
		text-align: center;
	}

	.btn {
		bottom: 20px;
		right: 20px;
	}

	.gift_item .el-icon-close {
		right: 10px;
		top: 10px;
	}

	.gift_item .el-icon-close:hover {
		color: #ff6a6c;
	}
</style>
